<?php

namespace Mapper;

class MemberAvatarModel extends \Mapper\Base\AbstractModel {
    use \Base\Model\TraitModel;

    protected $table = 'member_avatar';

    public function saveAvatar($uid, array $srcs) {
        $avatars = $this->avatars($uid);
        $time    = time();
        $sql     = sprintf('INSERT INTO `%s` (`uid`, `order`, `src`, `addtime`) VALUES ', $this->getTable());
        $items   = [];

        foreach ($srcs as $index => $src) {
            $items[] = sprintf("(%d, %d, '%s', %d)", $uid, $index, $src, $time);
        }

        $sql .= implode(',', $items);
        $sql .= sprintf(' ON DUPLICATE KEY UPDATE `lasttime` = %d, `src` = VALUES(`src`)', $time);

        try {
            $result = (bool)$this->query($sql);
        } catch(\Exception $e) {
            $result = false;
        }

        return $result;
    }

    /**
     * 用户头像组
     *
     * @param int $uid
     * @return array
     */
    public function avatars($uid) {
        $avatars = $this->fetchAll(['uid' => $uid], 'order');
        $items   = [];

        foreach ($avatars as $avatar) {
            if($avatar instanceof \MemberAvatarModel) {
                $items[$avatar->getId()] = $avatar->getSrc();
            }
        }

        return $items;
    }
}
